//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.tool.ahibernate.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.tool.ahibernate.annotation.Column;
import com.tool.ahibernate.annotation.Id;
import com.tool.ahibernate.annotation.Table;
import com.tool.ahibernate.util.TableHelper;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class BaseDaoImpl<T> implements BaseDao<T> {
    private String TAG = "AHibernate";
    private SQLiteOpenHelper dbHelper;
    private String tableName;
    private String idColumn;
    private Class<T> clazz;
    private List<Field> allFields;

    public BaseDaoImpl(SQLiteOpenHelper dbHelper) {
        this.dbHelper = dbHelper;
        this.clazz = (Class)((ParameterizedType)super.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        if(this.clazz.isAnnotationPresent(Table.class)) {
            Table table = (Table)this.clazz.getAnnotation(Table.class);
            this.tableName = table.name();
        }

        this.allFields = TableHelper.joinFields(this.clazz.getDeclaredFields(), this.clazz.getSuperclass().getDeclaredFields());
        Iterator var3 = this.allFields.iterator();

        while(var3.hasNext()) {
            Field field = (Field)var3.next();
            if(field.isAnnotationPresent(Id.class)) {
                Column column = (Column)field.getAnnotation(Column.class);
                this.idColumn = column.name();
                break;
            }
        }

    }

    public SQLiteOpenHelper getDbHelper() {
        return this.dbHelper;
    }

    public T get(int id) {
        String selection = this.idColumn + " = ?";
        String[] selectionArgs = new String[]{Integer.toString(id)};
        List<T> list = this.find((String[])null, selection, selectionArgs, (String)null, (String)null, (String)null, (String)null);
        return list != null && list.size() > 0?list.get(0):null;
    }

    private boolean isLocked(){
        SQLiteDatabase writeBase = this.dbHelper.getWritableDatabase();
        SQLiteDatabase readBase = this.dbHelper.getReadableDatabase();
        boolean result = writeBase.isDbLockedByCurrentThread() || readBase.isDbLockedByCurrentThread();
        writeBase.close();
        readBase.close();
        return result;
    }

    public List<T> rawQuery(String sql, String[] selectionArgs) {
        while(isLocked()) {
            try {
                Thread.sleep(30L);
            } catch (InterruptedException var12) {
                var12.printStackTrace();
            }
        }

        List<T> list = new ArrayList();
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = this.dbHelper.getReadableDatabase();
            cursor = db.rawQuery(sql, selectionArgs);
            this.getListFromCursor(list, cursor);
        } catch (Exception var11) {
            Log.e(this.TAG, "[rawQuery] from DB Exception.");
            var11.printStackTrace();
        } finally {
            if(cursor != null) {
                cursor.close();
            }

            if(db != null) {
                db.close();
            }

        }

        return list;
    }

    public boolean isExist(String sql, String[] selectionArgs) {
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = this.dbHelper.getReadableDatabase();
            cursor = db.rawQuery(sql, selectionArgs);
            if(cursor.getCount() > 0) {
                return true;
            }
        } catch (Exception var9) {
            Log.e(this.TAG, "[isExist] from DB Exception.");
            var9.printStackTrace();
        } finally {
            if(cursor != null) {
                cursor.close();
            }

            if(db != null) {
                db.close();
            }

        }

        return false;
    }

    public List<T> find() {
        return this.find((String[])null, (String)null, (String[])null, (String)null, (String)null, (String)null, (String)null);
    }

    public List<T> find(String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) {
        while(this.dbHelper.getReadableDatabase().isDbLockedByOtherThreads() || this.dbHelper.getReadableDatabase().isDbLockedByCurrentThread()) {
            Log.w(this.TAG, "find === db is locked by other or current threads!");

            try {
                Thread.sleep(10L);
            } catch (InterruptedException var17) {
                var17.printStackTrace();
            }
        }

        List<T> list = new ArrayList();
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = this.dbHelper.getReadableDatabase();
            cursor = db.query(this.tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
            this.getListFromCursor(list, cursor);
        } catch (Exception var16) {
            Log.e(this.TAG, "[find] from DB Exception");
            var16.printStackTrace();
        } finally {
            if(cursor != null) {
                cursor.close();
            }

            if(db != null) {
                db.close();
            }

        }

        return list;
    }

    private void getListFromCursor(List<T> list, Cursor cursor) throws IllegalAccessException, InstantiationException {
        label77:
        while(cursor.moveToNext()) {
            T entity = this.clazz.newInstance();
            Iterator var5 = this.allFields.iterator();

            while(true) {
                while(true) {
                    while(true) {
                        Field field;
                        Class fieldType;
                        int c;
                        do {
                            Column column;
                            do {
                                if(!var5.hasNext()) {
                                    list.add(entity);
                                    continue label77;
                                }

                                field = (Field)var5.next();
                                column = null;
                            } while(!field.isAnnotationPresent(Column.class));

                            column = (Column)field.getAnnotation(Column.class);
                            field.setAccessible(true);
                            fieldType = field.getType();
                            c = cursor.getColumnIndex(column.name());
                        } while(c < 0);

                        if(Integer.TYPE != fieldType && Integer.class != fieldType) {
                            if(String.class == fieldType) {
                                field.set(entity, cursor.getString(c));
                            } else if(Long.TYPE != fieldType && Long.class != fieldType) {
                                if(Float.TYPE != fieldType && Float.class != fieldType) {
                                    if(Short.TYPE != fieldType && Short.class != fieldType) {
                                        if(Double.TYPE != fieldType && Double.class != fieldType) {
                                            if(Blob.class == fieldType) {
                                                field.set(entity, cursor.getBlob(c));
                                            } else if(Character.TYPE == fieldType) {
                                                String fieldValue = cursor.getString(c);
                                                if(fieldValue != null && fieldValue.length() > 0) {
                                                    field.set(entity, Character.valueOf(fieldValue.charAt(0)));
                                                }
                                            }
                                        } else {
                                            field.set(entity, Double.valueOf(cursor.getDouble(c)));
                                        }
                                    } else {
                                        field.set(entity, Short.valueOf(cursor.getShort(c)));
                                    }
                                } else {
                                    field.set(entity, Float.valueOf(cursor.getFloat(c)));
                                }
                            } else {
                                field.set(entity, Long.valueOf(cursor.getLong(c)));
                            }
                        } else {
                            field.set(entity, Integer.valueOf(cursor.getInt(c)));
                        }
                    }
                }
            }
        }

    }

    public long insert(T entity) {
        SQLiteDatabase db = null;

        try {
            db = this.dbHelper.getWritableDatabase();
            ContentValues cv = new ContentValues();
            this.setContentValues(entity, cv, "create");
            long row = db.insert(this.tableName, (String)null, cv);
            long var7 = row;
            return var7;
        } catch (Exception var11) {
            Log.d(this.TAG, "[insert] into DB Exception.");
            var11.printStackTrace();
        } finally {
            if(db != null) {
                db.close();
            }

        }

        return 0L;
    }

    public void delete(int id) {
        SQLiteDatabase db = this.dbHelper.getWritableDatabase();
        String where = this.idColumn + " = ?";
        String[] whereValue = new String[]{Integer.toString(id)};
        db.delete(this.tableName, where, whereValue);
        db.close();
    }

    public void delete(Integer... ids) {
        if(ids.length > 0) {
            StringBuffer sb = new StringBuffer();

            for(int i = 0; i < ids.length; ++i) {
                sb.append('?').append(',');
            }

            sb.deleteCharAt(sb.length() - 1);
            SQLiteDatabase db = this.dbHelper.getWritableDatabase();
            String sql = "delete from " + this.tableName + " where " + this.idColumn + " in (" + sb + ")";
            db.execSQL(sql, ids);
            db.close();
        }

    }

    public void update(T entity) {
        SQLiteDatabase db = null;

        try {
            db = this.dbHelper.getWritableDatabase();
            ContentValues cv = new ContentValues();
            this.setContentValues(entity, cv, "update");
            String where = this.idColumn + " = ?";
            int id = Integer.parseInt(cv.get(this.idColumn).toString());
            cv.remove(this.idColumn);
            String[] whereValue = new String[]{Integer.toString(id)};
            db.update(this.tableName, cv, where, whereValue);
        } catch (Exception var10) {
            Log.d(this.TAG, "[update] DB Exception.");
            var10.printStackTrace();
        } finally {
            if(db != null) {
                db.close();
            }

        }

    }

    private void setContentValues(T entity, ContentValues cv, String type) throws IllegalAccessException {
        Iterator var5 = this.allFields.iterator();

        while(true) {
            Field field;
            Column column;
            Object fieldValue;
            do {
                do {
                    do {
                        if(!var5.hasNext()) {
                            return;
                        }

                        field = (Field)var5.next();
                    } while(!field.isAnnotationPresent(Column.class));

                    column = (Column)field.getAnnotation(Column.class);
                    field.setAccessible(true);
                    fieldValue = field.get(entity);
                } while(fieldValue == null);
            } while("create".equals(type) && field.isAnnotationPresent(Id.class));

            cv.put(column.name(), fieldValue.toString());
        }
    }

    public List<Map<String, String>> query2MapList(String sql, String[] selectionArgs) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        ArrayList retList = new ArrayList();

        try {
            db = this.dbHelper.getReadableDatabase();
            cursor = db.rawQuery(sql, selectionArgs);

            while(cursor.moveToNext()) {
                Map<String, String> map = new HashMap();
                String[] var10;
                int var9 = (var10 = cursor.getColumnNames()).length;

                for(int var8 = 0; var8 < var9; ++var8) {
                    String columnName = var10[var8];
                    map.put(columnName.toLowerCase(), cursor.getString(cursor.getColumnIndex(columnName)));
                }

                retList.add(map);
            }
        } catch (Exception var14) {
            Log.e(this.TAG, "[query2MapList] from DB exception");
            var14.printStackTrace();
        } finally {
            if(cursor != null) {
                cursor.close();
            }

            if(db != null) {
                db.close();
            }

        }

        return retList;
    }

    public void execSql(String sql, Object[] selectionArgs) {
        SQLiteDatabase db = null;

        try {
            db = this.dbHelper.getWritableDatabase();
            if(selectionArgs == null) {
                db.execSQL(sql);
            } else {
                db.execSQL(sql, selectionArgs);
            }
        } catch (Exception var8) {
            Log.e(this.TAG, "[execSql] DB exception.");
            var8.printStackTrace();
        } finally {
            if(db != null) {
                db.close();
            }

        }

    }
}
